const services_uuid1= "0000EEE0-0000-1000-8000-00805F9B34FB";
const services_uuid2= "0000FF00-0000-1000-8000-00805F9B34FB";
const services_uuid3= "49535343-FE7D-4AE5-8FA9-9FAFD205E455";
const ToBase64 = require('../../utils/base64gb2312.js');
const cpclExp = require('../../utils/cpcl-exp.js');


Page({
  data:{
    printList: [],    //打印机列表
    cArray: ['通用面单', '百世面单','韵达面单','邮政面单','短指令'],  //指令数组
    cIndex: 0,  //指令位置
    sendData64:[],
    showM: false,
    remark: '',
    remarkIndex:'',
    sysPlatform:''
  },
  onLoad:function(){
    var _this = this;

    _this.pickerData({detail:{value:'0'}});
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          sysPlatform: res.platform
        })   
      }
    })
  },
  onShow:function(){
    var list = wx.getStorageSync('printList');
    if(list.length > 0){
      this.setData({
        printList: list
      })
    }
  },
  pickerData:function(e){
    var index = e.detail.value;
    var data = '';
    this.setData({
      cIndex: index
    })
    switch (index) {
      case '0': data = cpclExp.val; break;
    };
    this.cutCommand(data);
  },
  //分包
  cutCommand:function(data){
    var sendData64 = [];
    var packageLength = 10;
    for (let i = 0; i < Math.ceil(data.length / packageLength); i++) {
      sendData64[i] = ToBase64.encode64gb2312(data.substr(i * packageLength, packageLength));
    }
    this.setData({
      sendData64: sendData64
    })
  },
  showActionSheet:function(res){
    var _this = this;
    var index = res.currentTarget.dataset.index;
    var printList = _this.data.printList;
    var deviceId = printList[index].deviceId;
    wx.showActionSheet({
      itemList: ['测试打印', '设置备注', '删除'],
      success: function (res) {
        switch (res.tapIndex){
          case 0: wx.navigateTo({
            url: '/pages/print/print?deviceId=' + deviceId,
          });break;// case 0: _this.testPrint(index); break;
          case 1: _this.setRemark(index); break;
          case 2: _this.deletePrint(index); break;
        }
      }
    })
  },
  //测试打印
  testPrint: function (index){
    this.start(index);
  },
  start: function (index) {
    var _this = this;
    // 初始化蓝牙适配器
    wx.openBluetoothAdapter({
      complete: function (res) {
        _this.getBluetoothAdapterState(index);
      }
    })
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState: function (index) {
    var _this = this;
    wx.getBluetoothAdapterState({
      complete: function (res) {
        if (!!res && res.available) {
          _this.startSearch(index);
        } else {
          _this.showTip("请开启手机蓝牙")
        }
      }
    })
  },
  //开始搜索
  startSearch: function (index) {
    var _this = this;
    wx.startBluetoothDevicesDiscovery({
      services: [],
      complete: function (res) {
        wx.showLoading({
          title: '连接打印机',
          mask: true
        })
        //区分安卓和ios设备
        if (_this.data.sysPlatform == 'ios'){
          _this.connectDevice(index);
        }else{
          setTimeout(function(){
            _this.connectDevice(index);
          },1000)
        }
      }
    })
  },
  connectDevice: function (index) {
    var _this = this;
    var printList = _this.data.printList;
    var deviceId = printList[index].deviceId;
    wx.createBLEConnection({
      deviceId: deviceId,
      success(res) {
        wx.showLoading({
          title: '正在传输...',
          mask: true
        });
        _this.getDeviceService(deviceId);
      },
      fail(res) {
        wx.hideLoading();
        _this.showTip('连接失败');
      }
    })
  },
  //搜索设备服务
  getDeviceService: function (deviceId) {
    var _this = this;
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        var serviceId = _this.filterService(res.services);
        if (serviceId != "") {
          _this.getDeviceCharacter(deviceId, serviceId);
        }else{
          _this.showTip('没有找到主服务');
          _this.closeBLEConnection(deviceId);
        }
      },
      fail: function (res) {
        _this.showTip('搜索设备服务失败');
        _this.closeBLEConnection(deviceId);
      }
    })
  },
  filterCharacter: function (characteristics){
    let writeId = '';
    for (let i = 0; i < characteristics.length; i++) {
      let charc = characteristics[i];
      if (charc.properties.write) {
        writeId = charc.uuid;
        break;
      }
    }
    return writeId;
  },
  filterService: function (services) {
    let serviceId = "";
    for (let i = 0; i < services.length; i++) {
      let serverid = services[i].uuid.toUpperCase();
      if (serverid.indexOf(services_uuid1) != -1 ||
        serverid.indexOf(services_uuid2) != -1 ||
        serverid.indexOf(services_uuid3) != -1
      ) {
        serviceId = services[i].uuid;
        break;
      }
    }
    return serviceId;
  },
  getDeviceCharacter: function (deviceId, serviceId) {
    var _this = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function (res) {
        let writeId = _this.filterCharacter(res.characteristics);
        if(writeId != ''){
          _this.writeBLECharacteristicValue(deviceId, serviceId, writeId,1);
        }else{
          _this.showTip('获取特征值失败');
          _this.closeBLEConnection(deviceId);
        }
      },
      fail: function (res) {
        _this.showTip('获取特征值失败');
        _this.closeBLEConnection(deviceId);
      }
    })
  },
  writeBLECharacteristicValue: function (deviceId, serviceId, writeId,times) {
    var _this = this;
    var sendData64 = _this.data.sendData64;
    if (sendData64.length >= times){
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: writeId,
        value: wx.base64ToArrayBuffer(sendData64[times - 1]),
        success: function (res) {
          _this.writeBLECharacteristicValue(deviceId, serviceId, writeId, ++times);
        },
        fail: function (res) {
          _this.showTip('传输失败');
          _this.closeBLEConnection(deviceId);
        }
      })
    }else{
      _this.showTip('传输完成');
      _this.closeBLEConnection(deviceId);
    }
  },
  closeBLEConnection: function (deviceId) {
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: function (res) {
      }
    })
  },
  //设置备注
  setRemark: function (index){
    var _this = this;
    var list = _this.data.printList;
    _this.setData({
      showM: true,
      remarkIndex: index
    })
    if (list[index].hasOwnProperty('remark')){
      _this.setData({
        remark: list[index].remark
      })
    }else{
      _this.setData({remark: ''})
    }
  },
  inputRemark:function(e){
    this.setData({
      remark:e.detail.value
    })
  },
  //删除打印机
  deletePrint: function (index){
    var _this = this;
    wx.showModal({
      content: '确认删除打印机？',
      success: function (res) {
        if (res.confirm) {
          var list = _this.data.printList;
          list.splice(index, 1);
          _this.upListdata(list);
        }
      }
    })
  },
  cancelR:function(){
    this.setData({
      showM: false
    })
  },
  confirmR:function(){
    var val = this.data.remark;
    var index = this.data.remarkIndex;
    var list = this.data.printList;
    list[index].remark = val;
    this.upListdata(list);
    this.cancelR();
  },
  upListdata: function (list){
    wx.setStorage({
      key: 'printList',
      data: list,
    })
    this.setData({
      printList: list
    })
  },
  showTip: function (data) {
    wx.hideLoading();
    wx.showModal({
      content: data,
      showCancel: false
    })
  }
})
